package com.tongtong.config.handler;

import com.ttio.netty.common.Constants;
import com.ttio.netty.enums.TypeIdentifierEnum;
import com.ttio.netty.message.MessageDetail;
import com.ttio.netty.thread.MessageThreadPool;
import com.ttio.netty.utils.ByteUtil;
import com.ttio.server.handler.MessageSocketHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * iccid拦截器
 *
 * @author zl
 */
public class SimICCIDServiceHandler extends SimpleChannelInboundHandler<MessageDetail> {
    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    private MessageSocketHandler messageSocketHandler;

    public SimICCIDServiceHandler(MessageSocketHandler messageSocketHandler) {
        this.messageSocketHandler = messageSocketHandler;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageDetail messageDetail) throws Exception {
        if (isSysInstruction(messageDetail.getTypeIdentifier().getValue())) {
            channelHandlerContext.channel().attr(Constants.SessionConfig.PING_COUNT).set(null);
            String iccid = ByteUtil.hexToString(ByteUtil.byteArrayToHexString(messageDetail.getMessages().getMessageInfos()));
            MessageThreadPool.getCachedThreadPool().execute(() -> {
                messageSocketHandler.channelAddHandler(channelHandlerContext);
            });
            return;
        }
        channelHandlerContext.fireChannelRead(messageDetail);
    }

    /**
     * @param @param  bytes
     * @param @return
     * @return boolean
     * @throws
     * @Title: isSysInstruction
     * @Description: TODO  判断是否是 系统报文
     */
    private boolean isSysInstruction(byte bytes) {
        // PIN引脚
        return bytes == 5;
    }
}
